<?php
// /material/2.0/openapi/search_word/applyKeywordsForChangeSearch


namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\Exception;
use StarCloud\Library\HttpCurl;
use StarCloud\Models\Doumvip\KkssDomain;
use StarCloud\Models\Doumvip\UserWhite;

class KuakeSearch
{
    protected $client_id = 462;
    protected $secret= "194e846405a54aaca6e8f43c02f0b5fb";
    protected $domain = "https://material-ug.uc.cn";

    use HttpCurl;

    /* @var $httpClient HttpClient */
    private $httpClient = null;

    public function __construct()
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function getHeader()
    {
        return [
            'Content-Type' => 'application/json',
        ];
    }

    public function getDomain()
    {
        return [
            [
                "label" => "影视/综艺",
                "id" => 4,
                'list' => array_column(KkssDomain::find([
                    'conditions' => 'status = 1 and type = 1',
                    'order' => 'updated_at desc'
                ])->toArray(), 'name')
            ],
            [
                "label" => "动漫",
                "id" => 3,
                'list' => array_column(KkssDomain::find([
                    'conditions' => 'status = 1 and type = 2',
                    'order' => 'updated_at desc'
                ])->toArray(), 'name')
            ]
        ];
    }

    public function getCategory()
    {
        // 搜索直达_
        return [
            '1' => ['id' => "1", "label" => '小说', "tag" => "xs_102"],
            '2' => ['id' => "2", "label" => '漫画', "tag" => "mh_104"],
            '3' => ['id' => "3", "label" => '动漫', "tag" => "dm_103"],
            '4' => ['id' => "4",  "label" => '影视/综艺', "tag" => "ys_101"],
        ];
    }

    public function create($keyword, $changeKeyWord, $tag, $doulamiId)
    {

        $tags = $this->getCategory();
        if (!isset($tags[$tag])) {
            throw new Exception(9999, "分类错误");
        }
        $url = $this->domain . '/material/2.0/openapi/search_word/applyKeywordsForChangeSearch?';
        $body = [
            'product' => 'QUARK',
            'keywords' => [
                ["keyword" => $keyword, "changeKeyword" => $changeKeyWord, "tag" => $tags[$tag]['tag']],
            ]
        ];
//        if (UserWhite::isKkWhiteSpecialUser($doulamiId)) {
            $body['kocUid'] = $doulamiId;
//        }

        $query = $this->sign();
        $url = $url . http_build_query($query);
        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        Di::getDefault()->get('logger')->info('kk_keyword' . $url . json_encode($json) . json_encode($body));
        if (isset($json['code']) && $json['code'] == "Sys.000") {
            return $json['data'];
        } else {
            throw new Exception(9999, $json['message'] ?? "夸克官方限制每天申请词总量， 次日再来申请");
        }
    }

    public function sign($params = [])
    {
        ksort($params);
        $params['sign'] = md5(http_build_query($params) . time()*1000 . $this->client_id . $this->secret);
        $params['clientId'] = $this->client_id;
        $params['timestamp'] = time()*1000;
        return $params;
    }

    public function getTaskOffLine($taskId)
    {
        $url = $this->domain . '/material/2.0/openapi/search_word/getKeywordsOfflineTime?';
        $body = [
            'taskIds' => [$taskId],
        ];
        $query = $this->sign($body);

        $response = $this->httpClient->sendPostRequest($url . http_build_query($query), $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        if (isset($json['code']) && $json['code'] == "Sys.000") {
            return  $json['data']['tasks'][0];
        }

        return false;

    }

    public function getTask($taskId)
    {
        $url = $this->domain . '/material/2.0/openapi/search_word/getResultForKeywordsApplication?';
        $body = [
            'taskId' => $taskId,
        ];
        $query = $this->sign($body);

        $response = $this->httpClient->sendGetRequest($url . http_build_query($query));

        $json = json_decode($response->getBody()->getContents(), true);
        var_dump($json);
        if (isset($json['code']) && $json['code'] == "Sys.000") {
            return  $json['data'];
        }

        return false;
    }
}